package org.dallasrowing.logbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.dallasrowing.logbook.ui.controller.LogBookUiController;
import org.dallasrowing.logbook.ui.controller.LogBookUiControllerImpl;
import org.dallasrowing.logbook.ui.view.SWTMainWindow;
import org.dallasrowing.model.dao.BoatsDAO;
import org.dallasrowing.model.dao.DamagesDAO;
import org.dallasrowing.model.dao.LogBookDAO;
import org.dallasrowing.model.dao.RowersDAO;
import org.dallasrowing.model.dao.sqlmap.SqlMapBoatsDAO;
import org.dallasrowing.model.dao.sqlmap.SqlMapDamagesDAO;
import org.dallasrowing.model.dao.sqlmap.SqlMapDaoFactory;
import org.dallasrowing.model.dao.sqlmap.SqlMapLogBookDao;
import org.dallasrowing.model.dao.sqlmap.SqlMapRowersDAO;


public class StartLogBook {

	public void run(Properties config) throws IOException {
		
		try
		{
			Config.conf = config;
			SqlMapDaoFactory.instance().initialize(config);
			BoatsDAO boatsDAO = new SqlMapBoatsDAO(SqlMapDaoFactory.instance().getSqlMap());
			RowersDAO rowersDAO = new SqlMapRowersDAO(SqlMapDaoFactory.instance().getSqlMap());
			LogBookDAO logBookDAO = new SqlMapLogBookDao(SqlMapDaoFactory.instance().getSqlMap());
			DamagesDAO damagesDAO = new SqlMapDamagesDAO(SqlMapDaoFactory.instance().getSqlMap());
		
			//set up the UI
			LogBookUiController controller = new LogBookUiControllerImpl(new SWTMainWindow(), boatsDAO, rowersDAO, logBookDAO, damagesDAO);
		
			//now run it!
			controller.create();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String propertiesFile = null;
		if (args.length != 1 )
		{
			System.err.println("Need to provide a properties file as parameter");
			System.out.println("Assuming logbook.properties as default...");
			propertiesFile = "logbook.properties";
		}
		else
		{
			propertiesFile = args[0];
		}
		
		Properties config = new Properties();
		try {
			
			config.load(new FileInputStream(propertiesFile));
			StartLogBook logbook = new StartLogBook();
			logbook.run(config);

		} catch (FileNotFoundException e) {
			System.err.println("Properties file "+propertiesFile+" does not exist!");
			return;
		} catch (IOException e) {
			System.err.println("Could not read properties in file:" + e.getMessage());
			return;
		}
		
	}

}
